//import {apiUrl,webUrl} from '../../config/prod.env'
// import { config } from '../../config/api'
import { getCookie } from '@/tools/cookie'
const prodEnv = require('../../config/prod.env')
export default async(url = '', data = {}, type = 'GET', method = 'fetch', apiUrl = '') => {
    type = type.toUpperCase();
    url = apiUrl + url;
    // console.log(data)

    if (type == 'GET') {
        let dataStr = ''; //数据拼接字符串
        if (data.length < 1) { return; }
        Object.keys(data).forEach(key => {
            dataStr += key + '=' + data[key] + '&';
        })

        if (dataStr !== '') {
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
            url = url + '?' + dataStr;
        }
    }

    if (window.fetch && method == 'fetch') {
        let requestConfig = {
            //设置成为include之后,既可以同域发送，也可以跨域发送 run dev时获取不到session，需run build放到容器中才可以
            credentials: 'include',
            method: type,
            headers: ({
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'token': getCookie('token')
            }),
            mode: "cors",
            cache: "no-cache"
        }

        if (type == 'POST') {
            Object.defineProperty(requestConfig, 'body', {
                value: typeof(data) == 'string' ? data : JSON.stringify(data)
            })
        }

        try {
            const response = await fetch(url, requestConfig);
            //如果后台设置了session头部为timeout表示需要登录
            //console.log(response.headers.get("sessionstatus")=== "timeout")
            if (response.headers.get("status") == "invalidReq") {
                window.location.href = prodEnv.webUrl
                return { code: "-1" }
            } else {
                const responseJson = await response.text();
                return responseJson
            }
        } catch (error) {
            throw new Error(error)
        }
    } else {
        return new Promise((resolve, reject) => {
            let requestObj;
            if (window.XMLHttpRequest) {
                requestObj = new XMLHttpRequest();
            } else {
                requestObj = new ActiveXObject;
            }
            //sg add for cors
            requestObj.withCredentials = true;

            let sendData = '';
            if (type == 'POST') {
                sendData = JSON.stringify(data);
            }

            requestObj.open(type, url, true);
            //sg modifided application/x-www-form-urlencoded with application/json
            requestObj.setRequestHeader("Content-type", "application/json");
            requestObj.send(sendData);

            requestObj.onreadystatechange = () => {
                if (requestObj.readyState == 4) {
                    if (requestObj.status == 200) {
                        let obj = requestObj.response
                        if (typeof obj !== 'object') {
                            obj = JSON.parse(obj);
                        }
                        resolve(obj)
                    } else {
                        reject(requestObj)
                    }
                }
            }
        })
    }
}
